package service;

import api.QrcodeApi;
import com.google.common.collect.ImmutableMap;
import common.pojo.CommonResult;
import common.utils.JsonUtils;

import common.utils.MyMapUtils;
import dao.WxUserInfoDao;
import httpclient.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import pojo.UserShopInfo;
import pojo.WxUserInfo;

import service.cfg.UserShopCfg;
import utils.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by asus on 2018/11/22.
 */
@Service
public class ChatAopService {
    public Logger logger = LoggerFactory.getLogger(ChatAopService.class);
    ThreadPoolExecutor threadPools;

    @Autowired
    WxUserInfoDao wxUserInfoDao;

    @Autowired
    QrcodeApi qrcodeApi;
    @Autowired
    UserShopCfg shopCfg;
    @Value("#{config['server.shopUser.url']}")
    String getShopId;
    @Autowired
    public ChatAopService(@Value("#{config['AsyncFramework.minThreadPoolSize']}") int minThreadPoolSize,
                          @Value("#{config['AsyncFramework.maxThreadPoolSize']}") int maxThreadSize,
                          @Value("#{config['AsyncFramework.threadKeepAliveTime']}") long getThreadKeepAliveTime) {
        threadPools = new ThreadPoolExecutor(minThreadPoolSize,
                maxThreadSize,
                getThreadKeepAliveTime, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>());
    }

    /**
     * 更新二维码
     *
     * @param
     */
      public void updateQrcode(WxUserInfo wxUserInfo){
          this.threadPools.execute(new Runnable() {
              @Override
              public void run() {
                 if(wxUserInfo.getQrCode()==null || StringUtils.isBlank(wxUserInfo.getQrCode())){
                     String token=qrcodeApi.getAccessToken();
                     if(StringUtils.isBlank(token)){
                        return;
                     }
                     Map map = new HashMap();
                     map.put("openId",wxUserInfo.getOpenId());
                     CommonResult result = HttpClientUtils.get(getShopId, ImmutableMap.of("wxId",wxUserInfo.getOpenId()));
                     UserShopInfo shopInfo = JsonUtils.objectToPojo(result.getData(), UserShopInfo.class);
                     if (shopInfo == null) {
                         return ;
                     }
                     map.put("shopId",shopInfo.getId());
                     map.put("headUrl",shopInfo.getLogo());
                     map.put("parentId",wxUserInfo.getId());
                     qrcodeApi.returnCode(map,token,wxUserInfo.getOpenId());
                 }
              }
          });
      }

    public void updateQrcodeMine(String openId,String headUrl){
        this.threadPools.execute(new Runnable() {
            @Override
            public void run() {
                    String token=qrcodeApi.getAccessToken();
                    if(StringUtils.isBlank(token)){
                        return;
                    }
                    Map map = new HashMap();
                    map.put("openId",openId);
                    map.put("headUrl",headUrl);
                    WxUserInfo wxUserInfo = wxUserInfoDao.getWxUserInfo(openId);
                    map.put("parentId",wxUserInfo.getId());
                   CommonResult result = HttpClientUtils.get(getShopId, ImmutableMap.of("wxId",wxUserInfo.getOpenId()));
                   if(result.isSuccess()){
                       UserShopInfo shopInfo = JsonUtils.objectToPojo(result.getData(), UserShopInfo.class);
                       if (shopInfo != null) {
                           map.put("shopId",shopInfo.getId());
                       }
                   }
                    qrcodeApi.returnCodeMine(map,token,openId);
            }
        });
    }


    public void addDistribution(String openId){
        this.threadPools.execute(new Runnable() {
            @Override
            public void run() {
                WxUserInfo userInfo = wxUserInfoDao.getWxUserInfo(openId);
                logger.warn(JsonUtils.toJson(MyMapUtils.beanToMap(userInfo,false)));
                CommonResult result = HttpClientUtils.post(shopCfg.addWxUser(), MyMapUtils.beanToMap(userInfo,false));
                logger.warn(result.getMessage()+result.getCode());
                logger.warn(JsonUtils.toJson(userInfo));

            }
        });


    }

}
